package com.kehutong.house.service;


import com.kehutong.common.urlconfig.FileUrlConfig;
import com.kehutong.house.entity.Parking;
import com.kehutong.house.entity.ParkingYard;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONArray;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.orm.jdbc.execute.entity.FindOne;
import org.coraframework.util.Objects;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@WebService("/basic/parking/service")
public class ParkingService {

	static final Logger logger = LoggerFactory.getLogger(ParkingService.class);

	private final static String businessType = "1104";

	@Inject
	private JdbcSession jdbcSession;

	@Inject
	private BasicService basicService;

	@Inject
	private FileUrlConfig fileUrlConfig;

	@ReqMapping("/list")
	public Object list(JSONObject jsonObject) {
		List<Parking> list = jdbcSession.findArray(Parking.class)
				.eq(jsonObject,  "classNo","ownerMobile","ownerNo","ownerCarNo")
				.in(jsonObject, "id")
				.in(jsonObject, "communityNo")
				.like(jsonObject, "name", "ownerName")
                .eq("deleted", false)
				.exe();

		list.forEach(item -> {
			ParkingYard yard = Pool.get(ParkingYard.class, item.getYardNo());
			if(Objects.nonNull(yard)){
				item.setYardName(yard.getName());
			}
		});

		return list;
	}

	@ReqMapping("/get")
	public Object get(Parking parking) {
		return parking;
	}

	@Bean(newInstance = true, copy = true)
	@ReqMapping("/save")
	public Object save(Parking parking) {
		jdbcSession.insert(parking);

		return parking;
	}

	@Bean(copy = true)
	@ReqMapping("/update")
	public Object update(Parking parking, JSONObject json) throws Exception {

		saveAttributeRecord(parking, json);

		jdbcSession.updateById(parking);

		return Result.success();
	}

	private void saveAttributeRecord(Parking entity, JSONObject jsonObject) throws Exception {
		if(Objects.isEmpty(entity.getOwnerNo())){
			return;
		}

		JSONObject json = new JSONObject();
		json.put("operateName", jsonObject.getString("operateName"));
		json.put("operateNo", jsonObject.getString("operateNo"));
		json.put("businessId", entity.getId());
		json.put("businessType", businessType);
		json.put("currentNo", entity.getOwnerNo());
		json.put("currentName", entity.getOwnerName());
		json.put("startTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern ("yyyy-MM-dd HH:mm:ss")));
		if(Objects.nonEmpty(entity.getOwnerNo())){
			Parking old = Pool.get(Parking.class, entity.getId());

			if(Objects.isEmpty(entity.getOwnerNo())){
				entity.setOwnerNo("");
			}

			if(Objects.isEmpty(old.getOwnerNo())){
				old.setOwnerNo("");
			}
			if(!Objects.equal(old.getOwnerNo(),entity.getOwnerNo())){
				json.put("beforeNo", old.getOwnerNo());
				json.put("beforeName", old.getOwnerName());
				JSONObject record = basicService.getAttributeRecord(json);
				if(Objects.nonEmpty(record)){
					record.put("endTime", LocalDateTime.now().format(DateTimeFormatter.ofPattern ("yyyy-MM-dd HH:mm:ss")));
					basicService.updateAttributeRecord(record);
				}
				basicService.saveAttributeRecord(json);
			}
		}
	}

	@ReqMapping("/delete")
	public Object delete(Parking parking) throws Exception {
		parking.setDeleted(true);
		jdbcSession.updateById(parking);

		return Result.success();
	}

    @ReqMapping("/batchUpdateParkingOwner")
	public Object batchUpdateParkingOwner(JSONObject jsonObject){
	    List<Parking> list = jdbcSession.findArray(Parking.class)
                .eq(jsonObject,"ownerNo")
                .eq("deleted", false)
                .exe();

        list.forEach(item->{
            item.setOwnerNo(jsonObject.getString("ownerNo"));
            item.setOwnerName(jsonObject.getString("ownerName"));
            item.setOwnerMobile(jsonObject.getString("ownerMobile"));
        });

        jdbcSession.updateById(list);
        return Result.success();
    }

	@ReqMapping("/getParkingInfo")
	public Object getParkingInfo(JSONObject jsonObject){

		JSONArray array = jsonObject.getJSONArray("list");
		List<JSONObject> list = JSONObject.parseArray(array.toJSONString(), JSONObject.class);

		List<JSONObject> result = new ArrayList<>();
		list.forEach(json ->{
			ParkingYard yard = jdbcSession.findOne(ParkingYard.class)
					.eq("name", json.getString("yardName"))
					.eq("deleted", false)
					.exe();

			if(Objects.nonNull(yard)){
				json.put("yardNo", yard.getId());
			}
			json.put("name", json.getString("parkingName"));

			Parking parking = jdbcSession.findOne(Parking.class)
					.eq(json, "name", "communityName", "yardNo")
					.eq("deleted", false).exe();

			if(Objects.nonNull(parking)){
				StringBuilder builder = new StringBuilder();
				builder.append(parking.getCommunityName()).append("-")
						.append(yard.getName()).append("-");
				builder.append(parking.getName());

				json.put("info", builder.toString());
				json.put("id",parking.getId());
				result.add(json);
			}
		});
		return result;
	}
}
